package com.two.screen.water.balance.ui.activity

import android.annotation.SuppressLint
import android.app.AlertDialog
import android.bluetooth.BluetoothAdapter
import android.content.Intent
import android.os.Bundle
import android.view.KeyEvent
import android.view.View
import android.widget.TextView
import androidx.appcompat.widget.SwitchCompat
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.SimpleItemAnimator
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.chad.library.adapter.base.BaseMultiItemQuickAdapter
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.cyItem.sesrialPort.SerialPortFinder
import com.jakewharton.rxbinding2.view.RxView
import com.two.screen.water.balance.R
import com.two.screen.water.balance.bean.ItemBean
import com.two.screen.water.balance.bean.WeightBean
import com.two.screen.water.balance.net.api.DataApi
import com.two.screen.water.balance.permission.PermissionUtil
import com.two.screen.water.balance.print.PrinterAll
import com.two.screen.water.balance.print.android_print.bluetooth.BluetoothDeviceList
import com.two.screen.water.balance.print.android_print.bluetooth.BluetoothPrinter
import com.two.screen.water.balance.ui.App
import com.two.screen.water.balance.ui.activity.base.BaseActivity
import com.two.screen.water.balance.ui.service.AppService
import com.two.screen.water.balance.utils.*
import com.two.screen.water.balance.utils.eventbus.Event
import com.two.screen.water.balance.utils.eventbus.EventBusUtil
import com.two.screen.water.balance.utils.eventbus.EventCode
import com.two.screen.water.balance.utils.voice.VoicePlay
import com.two.screen.water.balance.widget.DividerItemDecoration
import kotlinx.android.synthetic.main.activity_function_menu.mGoBackLayout
import kotlinx.android.synthetic.main.activity_system_setting.*
import java.util.concurrent.TimeUnit

@Route(path = ARouterUtils.SystemSettingActivity)
class SystemSettingActivity : BaseActivity() {
    override fun getContentLayout(): Any = R.layout.activity_system_setting
    lateinit var mLeftAdapter: LeftAdapter
    lateinit var mRightAdapter: RightAdapter
    private var mIsDebug = false

    /*菜单数据*/
    private var mList: MutableList<ItemBean> = getItemList()
    private var mAllDevicesSerialPortArray: Array<String> = SerialPortFinder().allDevicesPath

    @SuppressLint("NotifyDataSetChanged")
    private fun refreshList() {
        mList = getItemList()
        mList.first().isSelected = false
        var index = -1
        for (i in mLeftAdapter.data.indices) {
            if (mLeftAdapter.data[i].isSelected) index = i;
        }
        if (index == -1) {
            index = 0
            mList.first().isSelected = true
        }
        mLeftAdapter.setNewData(mList)
        mRightAdapter.setNewData(mLeftAdapter.data[index].list)
        mLoadingDialog.dismiss()
    }

    private fun getItemList(): MutableList<ItemBean> {
        var leftList = mutableListOf<ItemBean>()

        val element01 = ItemBean().apply {
            this.leftName = "外部设备";isSelected = true
            val rightList01 = mutableListOf<ItemBean>()
            rightList01.add(ItemBean().apply { this.leftName = "打印设备" })
            rightList01.add(ItemBean(1).apply { leftName = "USB小票打印机";rightValue = DataApi.mPrinterTypeArray[DataApi.mPrinterTypeIndex];rightSubValue = getSubValuePrint() })
            rightList01.add(ItemBean(1).apply { leftName = "USB标签打印机";rightValue = "暂无支持" })
            rightList01.add(ItemBean(1).apply { leftName = "蓝牙打印机";rightValue = getBluetoothPrintStatues(); rightSubValue = getBluetoothPrintInfo() })
            rightList01.add(ItemBean().apply { this.leftName = "电子秤设置" })
            rightList01.add(ItemBean(1).apply { leftName = "电子秤类型";rightValue = DataApi.mScaleTypeArray[DataApi.mScaleTypeIndex];rightSubValue = getSubValueWeight() })
            rightList01.add(ItemBean(1).apply { leftName = "电子秤串口";rightValue = DataApi.mWeightSerialPortPath })
            rightList01.add(ItemBean(1).apply { leftName = "电子秤波特率";rightValue = "9600";isClicked = false })
            rightList01.add(ItemBean().apply { this.leftName = "读卡器设置" })
            rightList01.add(ItemBean(1).apply { leftName = "读卡器类型";rightValue = DataApi.mReaderArray[DataApi.mReaderIndex];rightSubValue = getSubValueReader() })
            rightList01.add(ItemBean(1).apply { leftName = "读卡器串口";rightValue = DataApi.mReaderSerialPortPath })
            rightList01.add(ItemBean(1).apply { leftName = "读卡器波特率";rightValue = "9600";isClicked = false })
            this.list = rightList01
        }
        leftList.add(element01)
        leftList.add(ItemBean().apply {
            this.leftName = "收银小票机设置"
            this.list = mutableListOf(
                ItemBean().apply { this.leftName = "设置" },
                ItemBean(1).apply { leftName = "小票机打印张数";rightValue = DataApi.mBillPrintTimesArray[DataApi.mBillPrintTimesIndex] },
                ItemBean(1).apply { leftName = "打印纸宽度";rightValue = DataApi.mPrintPaperWidthArray[DataApi.mPrintPaperWidthIndex] },
                ItemBean(2).apply { leftName = "收据打印logo";isChecked = false },
                ItemBean(2).apply { leftName = "收据打印反馈二维码";isChecked = true }
            )
        })
        leftList.add(ItemBean().apply {
            this.leftName = "副屏设置"
            this.list = mutableListOf(
                ItemBean().apply { this.leftName = "常规设置" },
                ItemBean(2).apply { leftName = "是否开启副屏显示";isChecked = DataApi.mIsShowViceDisplay },
                ItemBean(2).apply { leftName = "是否开启副屏广告";isChecked = DataApi.mIsShowViceBanner },
                ItemBean(1).apply { leftName = "广告播放模式";rightValue = DataApi.mBannerPlayTypeArray[DataApi.mBannerPlayTypeIndex] },
                ItemBean().apply { this.leftName = "时间设置" },
                ItemBean(1).apply { leftName = "完成订单后,副屏多久进入广告(单位秒)";rightValue = DataApi.mIntoBannerTimeArray[DataApi.mIntoBannerTimeIndex] },
                ItemBean(1).apply { leftName = "每张广告图轮播的时长(单位秒)";rightValue = DataApi.mPerBannerImgStayTimeArray[DataApi.mPerBannerImgStayTimeIndex] }
            )
        })
        leftList.add(ItemBean().apply {
            this.leftName = "AI识别"
            this.list = mutableListOf(
                ItemBean().apply { this.leftName = "算法设置" },
                ItemBean(1).apply { leftName = "使用何种AI识别算法";rightValue = DataApi.mAiBrandTypeArray[DataApi.mAiBrandTypeIndex] },
                ItemBean().apply { this.leftName = "其它设置" },
                ItemBean(1).apply { leftName = "授权激活";rightValue = "请点击" },
                ItemBean(1).apply { leftName = "内部设置";rightValue = "进入插件设置" },
                ItemBean(1).apply { leftName = "学习模式";rightValue = "进入学习模式" },
                //ItemBean(1).apply { leftName = "商品管理";rightValue = "进入商品管理" },
                ItemBean(1).apply { leftName = "清除全部商品的学习数据";rightValue = "请点击" },
            )
        })
//        leftList.add(ItemBean().apply {
//            this.leftName = "数据管理"
//            this.list = mutableListOf(
//                ItemBean().apply { this.leftName = "本地数据备份" },
//                ItemBean(1).apply { leftName = "全部备份";rightValue = "点击开始备份" },
//                ItemBean().apply { this.leftName = "本地数据恢复" },
//                ItemBean(1).apply { leftName = "全部恢复";rightValue = "点击开始恢复" }
//            )
//        })
        leftList.add(ItemBean().apply {
            this.leftName = "其他设置"
            this.list = mutableListOf(
                ItemBean().apply { this.leftName = "图标显示" },
                ItemBean(2).apply { leftName = "是否开启电量显示";isChecked = DataApi.mIsShowBatteryChanged },
                ItemBean(2).apply { leftName = "是否开启蓝牙打印显示";isChecked = DataApi.mIsShowBluetoothPrinter },
                ItemBean().apply { this.leftName = "语音设置" },
                ItemBean(2).apply { leftName = "是否开启支付语音播报";isChecked = DataApi.mIsOpenPayVoice },
            )
        })
        leftList.add(ItemBean().apply {
            this.leftName = "系统信息"
            this.list = mutableListOf(
                ItemBean().apply { this.leftName = "公司信息" },
                ItemBean(1).apply { leftName = "公司名称";rightValue = "食安慧（深圳）科技股份有限公司";isClicked = false },
                ItemBean(1).apply { leftName = "联系我们";rightValue = "400-808-0738";isClicked = false },
                ItemBean(1).apply { leftName = "官网地址";rightValue = "http://www.rdxsaj.com/";isClicked = false },
                ItemBean().apply { this.leftName = "软件信息" },
                ItemBean(1).apply { leftName = "设备号";rightValue = DataApi.mAppUnitId;isClicked = false },
                ItemBean(1).apply { leftName = "版本号";rightValue = CommUtils.getAppVersionName() }
            )
        })

        return leftList
    }

    private fun getBluetoothPrintInfo(): String? {
        var info: String? = null
        if (BluetoothPrinter.mBluetoothPrinterMac != null && BluetoothPrinter.mBluetoothPrinterMac!!.isNotBlank()) {
            info = "Mac：${BluetoothPrinter.mBluetoothPrinterMac}; NAME：${BluetoothPrinter.mBluetoothPrinterName}"
        }
        return info
    }

    private fun getBluetoothPrintStatues(): String {
        var mac = "未连接"
        if (BluetoothPrinter.isConnected) mac = "已连接"
        d("getBluetoothPrintStatues-statues:$mac")
        return mac
    }

    //获取打印的 设备地址
    private fun getSubValuePrint(): String? {
        return if (DataApi.mPrinterTypeIndex != 0) DataApi.mUSBDevicePath else null
    }

    //获取秤体的 设备地址
    private fun getSubValueWeight(): String? {
        return if (DataApi.mScaleTypeIndex != 0) "串口:${DataApi.mSerialPortPathWeight},波特率:${DataApi.mSerialPortPortWeight}" else null
    }

    //获取读卡器的 设备地址
    private fun getSubValueReader(): String? {
        return if (DataApi.mReaderIndex != 0) "串口:${DataApi.mSerialPortPathReader},波特率:${DataApi.mSerialPortPortReader}" else null
    }

    override fun initView(savedInstanceState: Bundle?) {

        mDebugReaderTv.visibility = if (DataApi.mReaderIndex == 0) View.GONE else View.VISIBLE
    }

    override fun initData() {
        initLeftRecyclerView()
        initRightRecyclerView()
    }

    private fun initRightRecyclerView() {
        (mRightRecyclerView.itemAnimator as SimpleItemAnimator).supportsChangeAnimations = false //去闪烁
        //mRightRecyclerView?.addItemDecoration(DividerItemDecoration(this, DividerItemDecoration.HORIZONTAL_LIST, 1, ContextCompat.getColor(App.context!!, R.color.line_color), false))
        mRightAdapter = RightAdapter()
        mRightRecyclerView.layoutManager = LinearLayoutManager(this)
        mRightRecyclerView.adapter = mRightAdapter
        mRightAdapter.bindToRecyclerView(mRightRecyclerView)
        mRightAdapter.setEmptyView(R.layout.layout_status_layout_manager_empty3)

        val first = mList.first()
        mRightTitleTv.text = first.leftName
        mRightAdapter.setNewData(first.list)
    }

    private fun initLeftRecyclerView() {
        (mLeftRecyclerView.itemAnimator as SimpleItemAnimator).supportsChangeAnimations = false //去闪烁
        mLeftRecyclerView?.addItemDecoration(DividerItemDecoration(this, DividerItemDecoration.HORIZONTAL_LIST, 1, ContextCompat.getColor(App.context!!, R.color.line_color), true))
        mLeftAdapter = LeftAdapter()
        mLeftRecyclerView.layoutManager = LinearLayoutManager(this)
        mLeftRecyclerView.adapter = mLeftAdapter
        mLeftAdapter.bindToRecyclerView(mLeftRecyclerView)
        mLeftAdapter.setEmptyView(R.layout.layout_status_layout_manager_empty3)
        mLeftAdapter.setNewData(mList)
    }

    @SuppressLint("ClickableViewAccessibility", "CheckResult", "NotifyDataSetChanged")
    override fun initListener() {
        RxView.clicks(mDebugPlayVoiceBtn)
            .throttleFirst(1, TimeUnit.SECONDS)
            .subscribe {
                if (!DataApi.mIsOpenPayVoice) {
                    ToastUtil.showToast("付语音播报未开启!")
                    return@subscribe
                }
                VoicePlay.with(this).testPlay()
            }
        RxView.clicks(mDebugBluetoothPrintTv)
            .throttleFirst(1, TimeUnit.SECONDS)
            .subscribe {
                PrinterAll.printerTest(true)
            }
        RxView.clicks(mDebugUSBPrintTv)
            .throttleFirst(1, TimeUnit.SECONDS)
            .subscribe {
                PrinterAll.printerTest()
            }
        mRightTitleTv?.setOnClickListener {
            var printer = BluetoothPrinter.myOpertion?.printer
            d("bluetooth connect:${BluetoothPrinter.isConnected}，printer connect:${printer?.isConnected}")
            mDebugBluetoothPrintTv.visibility = if (printer?.isConnected == true) View.VISIBLE else View.GONE
            mIsDebug = !mIsDebug
            mDebugLayout.visibility = if (mIsDebug) View.VISIBLE else View.GONE

        }
        mGoBackLayout.setOnClickListener { goBack() }
        RxView.clicks(mRestartTv)
            .throttleFirst(1, TimeUnit.SECONDS)
            .subscribe {
            }
    }


    /*左边列表 适配器*/
    inner class LeftAdapter : BaseQuickAdapter<ItemBean, BaseViewHolder>(R.layout.item_system_setting_left, null) {
        @SuppressLint("CheckResult")
        override fun convert(helper: BaseViewHolder, item: ItemBean) {
//            helper
//                .setText(R.id.item_tv1, " ● ")
            helper.getView<View>(R.id.item_root_view).apply {
                this.isSelected = item.isSelected
                setOnClickListener {
                    val position = helper.bindingAdapterPosition
                    var lastIndex = mData.indices.find { mData[it].isSelected }
                    lastIndex?.let {
                        mData[lastIndex].isSelected = false
                        notifyItemChanged(lastIndex)
                    }
                    val itemBean = mData[position]
                    itemBean.isSelected = true
                    notifyItemChanged(position)
                    //TODO:这里还需要刷新右边数据。
                    mRightTitleTv.text = itemBean.leftName
                    mRightAdapter.setNewData(itemBean.list)
                }
            }
            helper.getView<TextView>(R.id.item_tv1).apply {
                this.isSelected = item.isSelected
            }
            helper.getView<TextView>(R.id.item_tv2).apply {
                this.isSelected = item.isSelected
                this.text = item.leftName
            }

        }
    }

    /*右边列表 适配器*/
    inner class RightAdapter : BaseMultiItemQuickAdapter<ItemBean, BaseViewHolder>(null) {

        init {
            addItemType(0, R.layout.item_system_setting_title)
            addItemType(1, R.layout.item_system_setting_option)
            addItemType(2, R.layout.item_system_setting_switch)
        }

        override fun convert(helper: BaseViewHolder, item: ItemBean) {
            when (item.item_type) {
                0 -> helper.setText(R.id.item_tv1, item.leftName)
                2 -> {
                    helper
                        .setText(R.id.item_tv1, item.leftName)
                        .getView<SwitchCompat>(R.id.item_switch).apply {
                            isChecked = item.isChecked
                            text = if (isChecked) "开启" else "关闭"
                            this.setOnCheckedChangeListener { buttonView, isChecked ->
                                if (!buttonView.isPressed) return@setOnCheckedChangeListener
                                var data = mData[helper.bindingAdapterPosition]
                                data.isChecked = isChecked
                                text = if (isChecked) "开启" else "关闭"
                                when (data.leftName) {
                                    "是否开启副屏显示" -> {
                                        //保存状态
                                        DataApi.mIsShowViceDisplay = isChecked
                                        SPUtils.putBoolean(Params.mIsShowViceDisplay, isChecked)
                                        ToastUtil.showToast("设置成功，建议重启APP，避免没生效。")
                                    }
                                    "是否开启副屏广告" -> {
                                        DataApi.mIsShowViceBanner = isChecked
                                        SPUtils.putBoolean(Params.mIsShowViceBanner, isChecked)
                                        ToastUtil.showToast("设置成功，建议重启APP，避免没生效。")
                                    }
                                    "是否开启电量显示" -> {
                                        DataApi.mIsShowBatteryChanged = isChecked
                                        SPUtils.putBoolean(Params.mIsShowBatteryChanged, isChecked)
                                        EventBusUtil.sendEvent(Event(if (isChecked) EventCode.BATTERY_CHANGED_REGISTER else EventCode.BATTERY_CHANGED_UNREGISTER))
                                        mLoadingDialog.show()
                                        mLoadingDialog.titleTv.text = if (isChecked) "正在打开..." else "正在关闭..."
                                        mGoBackLayout.postDelayed({ mLoadingDialog.dismiss() }, 2000)
                                    }
                                    "是否开启蓝牙打印显示" -> {
                                        DataApi.mIsShowBluetoothPrinter = isChecked
                                        SPUtils.putBoolean(Params.mIsShowBluetoothPrinter, isChecked)
                                        EventBusUtil.sendEvent(Event(EventCode.BLUETOOTH_PRINT_IS_SHOW, isChecked))
                                    }
                                    "是否开启支付语音播报" -> {
                                        DataApi.mIsOpenPayVoice = isChecked
                                        SPUtils.putBoolean(Params.mIsOpenPayVoice, isChecked)
                                    }
                                    else -> ToastUtil.showToast("暂不开放此功能!")
                                }
                            }
                        }
                }
                else -> {
                    helper
                        .setText(R.id.item_tv1, item.leftName)
                        .setText(R.id.item_tv2, item.rightValue?.toString())
                        .setGone(R.id.item_iv, item.isClicked)
                        .getView<TextView>(R.id.item_tv3).apply {
                            visibility = if (item.rightSubValue.isNullOrBlank()) View.GONE else View.VISIBLE
                            text = if (item.rightSubValue.isNullOrBlank()) "" else "${item.rightSubValue}"
                        }
                    helper.itemView.setOnClickListener {
                        val position = helper.bindingAdapterPosition
                        val itemBean = mData[position]
                        if (!itemBean.isClicked) return@setOnClickListener
                        when (itemBean.leftName) {
                            "全部备份" -> {
                                //TODO:这里可能需要访问本地文件权限
                                PermissionUtil.requestPermission(this@SystemSettingActivity, PermissionUtil.READ_PHONE_STATE, {
                                    com.two.screen.water.balance.permission.AlertDialog.newBuilder(this@SystemSettingActivity)
                                        .setCancelable(true)
                                        .setTitle("备份")
                                        .setMessage("是否覆盖之前备份数据？")
                                        .setPositiveButton(R.string.confirm) { dialog, which ->
                                            DbUtils.exportDB(this@SystemSettingActivity, App.mDbDir, App.mDbName);
                                            ToastUtil.showToast("数据备份成功!")
                                            dialog.dismiss()
                                        }
                                        .setNegativeButton(R.string.cancel) { dialog, which -> dialog.dismiss() }
                                        .show()
                                })
                            }
                            "全部恢复" -> {
                                PermissionUtil.requestPermission(this@SystemSettingActivity, PermissionUtil.READ_PHONE_STATE, {
                                    DbUtils.importDB(this@SystemSettingActivity, App.mDbDir, App.mDbName);
                                    ToastUtil.showToast("数据恢复成功，请重启APP")
                                })
                            }
                            "USB小票打印机" -> {
                                AlertDialog.Builder(this@SystemSettingActivity)
                                    .setTitle("请选择打印机类型:")
                                    .setCancelable(true)
                                    ?.setSingleChoiceItems(DataApi.mPrinterTypeArray, DataApi.mPrinterTypeIndex) { dialog, which -> // [1]把选择的条目给取出来
                                        itemBean.rightValue = DataApi.mPrinterTypeArray[which]
                                        DataApi.mPrinterTypeIndex = which
                                        //保存当前USB小票打印机秤状态
                                        SPUtils.putInt(Params.mPrinterTypeIndex, DataApi.mPrinterTypeIndex)
                                        notifyItemChanged(position)
                                        ToastUtil.showToast("设置成功，重启APP才能生效。")
                                        dialog.dismiss()
                                    }
                                    ?.show()?.apply { DialogUtil.hideNavigationBar(window) }
                            }
                            "蓝牙打印机" -> {
                                d("BluetoothPrinter.isConnected：${BluetoothPrinter.isConnected}")
                                PermissionUtil.requestPermission(this@SystemSettingActivity, PermissionUtil.READ_PHONE_STATE, {
                                    if (BluetoothPrinter.isConnected) {        //如果已经连接了, 则断开
                                        AlertDialog.Builder(this@SystemSettingActivity)
                                            .setTitle(R.string.str_message)
                                            .setMessage("是否断开连接？")
                                            .setPositiveButton("断开连接") { dialog, arg1 ->
                                                EventBusUtil.sendEvent(Event(EventCode.BLUETOOTH_PRINT_CLOSE))
                                                BluetoothPrinter.mBluetoothPrinterMac = null
                                                BluetoothPrinter.mBluetoothPrinterName = null
                                                SPUtils.putString(Params.mBluetoothPrinterMac, null)
                                                SPUtils.putString(Params.mBluetoothPrinterName, null)
                                                refreshList()
                                            }
                                            .show()
                                    } else {
                                        EventBusUtil.sendEvent(Event(EventCode.BLUETOOTH_PRINT_REBIND))
                                    }
                                })
                            }
                            "电子秤类型" -> {
                                AlertDialog.Builder(this@SystemSettingActivity)
                                    .setTitle("请选择电子秤类型:")
                                    .setCancelable(true)
                                    ?.setSingleChoiceItems(DataApi.mScaleTypeArray, DataApi.mScaleTypeIndex) { dialog, which -> // [1]把选择的条目给取出来
                                        itemBean.rightValue = DataApi.mScaleTypeArray[which]
                                        DataApi.mScaleTypeIndex = which
                                        //保存当前电子秤状态
                                        SPUtils.putInt(Params.mScaleTypeIndex, DataApi.mScaleTypeIndex)
                                        notifyItemChanged(position)
                                        ToastUtil.showToast("设置成功，重启APP才能生效。")
                                        dialog.dismiss()
                                    }
                                    ?.show()?.apply { DialogUtil.hideNavigationBar(window) }
                            }
                            "电子秤串口" -> {
                                if (mAllDevicesSerialPortArray.isEmpty()) {
                                    ToastUtil.showToast("没有找到任何串口!!")
                                    return@setOnClickListener
                                }
                                var index = mAllDevicesSerialPortArray.indices.find { mAllDevicesSerialPortArray[it] == DataApi.mWeightSerialPortPath } ?: 0
                                AlertDialog.Builder(this@SystemSettingActivity)
                                    .setTitle("请选择电子秤串口地址:")
                                    .setCancelable(true)
                                    ?.setSingleChoiceItems(mAllDevicesSerialPortArray, index) { dialog, which -> // [1]把选择的条目给取出来
                                        DataApi.mWeightSerialPortPath = mAllDevicesSerialPortArray[which]
                                        //保存
                                        SPUtils.putString(Params.mWeightSerialPortPath, DataApi.mWeightSerialPortPath)
                                        mData[position].rightValue = DataApi.mWeightSerialPortPath
                                        notifyItemChanged(position)
                                        ToastUtil.showToast("设置成功，重启APP才能生效。")
                                        dialog.dismiss()
                                    }
                                    ?.show()?.apply { DialogUtil.hideNavigationBar(window) }
                            }
                            "读卡器串口" -> {
                                if (mAllDevicesSerialPortArray.isEmpty()) {
                                    ToastUtil.showToast("没有找到任何串口!!")
                                    return@setOnClickListener
                                }
                                var index = mAllDevicesSerialPortArray.indices.find { mAllDevicesSerialPortArray[it] == DataApi.mReaderSerialPortPath } ?: 0
                                AlertDialog.Builder(this@SystemSettingActivity)
                                    .setTitle("请选择读卡器串口地址:")
                                    .setCancelable(true)
                                    ?.setSingleChoiceItems(mAllDevicesSerialPortArray, index) { dialog, which -> // [1]把选择的条目给取出来
                                        DataApi.mReaderSerialPortPath = mAllDevicesSerialPortArray[which]
                                        //保存
                                        SPUtils.putString(Params.mReaderSerialPortPath, DataApi.mReaderSerialPortPath)
                                        mData[position].rightValue = DataApi.mReaderSerialPortPath
                                        notifyItemChanged(position)
                                        ToastUtil.showToast("设置成功，重启APP才能生效。")
                                        dialog.dismiss()
                                    }
                                    ?.show()?.apply { DialogUtil.hideNavigationBar(window) }
                            }
                            "读卡器类型" -> {
                                AlertDialog.Builder(this@SystemSettingActivity)
                                    .setTitle("请选择读卡器类型:")
                                    .setCancelable(true)
                                    ?.setSingleChoiceItems(DataApi.mReaderArray, DataApi.mReaderIndex) { dialog, which -> // [1]把选择的条目给取出来
                                        itemBean.rightValue = DataApi.mReaderArray[which]
                                        DataApi.mReaderIndex = which
                                        //保存当前电子秤状态
                                        SPUtils.putInt(Params.mReaderIndex, DataApi.mReaderIndex)
                                        notifyItemChanged(position)
                                        ToastUtil.showToast("设置成功，重启APP才能生效。")
                                        dialog.dismiss()
                                    }
                                    ?.show()?.apply { DialogUtil.hideNavigationBar(window) }
                            }
                            "小票机打印张数" -> {
                                AlertDialog.Builder(this@SystemSettingActivity)
                                    .setTitle("请选择小票机打印张数:")
                                    .setCancelable(true)
                                    ?.setSingleChoiceItems(DataApi.mBillPrintTimesArray, DataApi.mBillPrintTimesIndex) { dialog, which -> // [1]把选择的条目给取出来
                                        itemBean.rightValue = DataApi.mBillPrintTimesArray[which]
                                        DataApi.mBillPrintTimesIndex = which
                                        SPUtils.putInt(Params.mBillPrintTimesIndex, DataApi.mBillPrintTimesIndex)
                                        notifyItemChanged(position)
                                        dialog.dismiss()
                                    }
                                    ?.show()?.apply { DialogUtil.hideNavigationBar(window) }
                            }
                            "打印纸宽度" -> {
                                AlertDialog.Builder(this@SystemSettingActivity)
                                    .setTitle("请选择打印纸宽度:")
                                    .setCancelable(true)
                                    ?.setSingleChoiceItems(DataApi.mPrintPaperWidthArray, DataApi.mPrintPaperWidthIndex) { dialog, which -> // [1]把选择的条目给取出来
                                        itemBean.rightValue = DataApi.mPrintPaperWidthArray[which]
                                        DataApi.mPrintPaperWidthIndex = which
                                        SPUtils.putInt(Params.mPrintPaperWidthIndex, DataApi.mPrintPaperWidthIndex)
                                        notifyItemChanged(position)
                                        dialog.dismiss()
                                    }
                                    ?.show()?.apply { DialogUtil.hideNavigationBar(window) }
                            }
                            "广告播放模式" -> {
                                AlertDialog.Builder(this@SystemSettingActivity)
                                    .setTitle("请选择广告播放模式:")
                                    .setCancelable(true)
                                    ?.setSingleChoiceItems(DataApi.mBannerPlayTypeArray, DataApi.mBannerPlayTypeIndex) { dialog, which -> // [1]把选择的条目给取出来
                                        itemBean.rightValue = DataApi.mBannerPlayTypeArray[which]
                                        DataApi.mBannerPlayTypeIndex = which
                                        SPUtils.putInt(Params.mBannerPlayTypeIndex, DataApi.mBannerPlayTypeIndex)
                                        notifyItemChanged(position)
                                        dialog.dismiss()
                                    }
                                    ?.show()?.apply { DialogUtil.hideNavigationBar(window) }
                            }
                            "完成订单后,副屏多久进入广告(单位秒)" -> {
                                AlertDialog.Builder(this@SystemSettingActivity)
                                    .setTitle("请选择时间(单位秒):")
                                    .setCancelable(true)
                                    ?.setSingleChoiceItems(DataApi.mIntoBannerTimeArray, DataApi.mIntoBannerTimeIndex) { dialog, which -> // [1]把选择的条目给取出来
                                        itemBean.rightValue = DataApi.mIntoBannerTimeArray[which]
                                        DataApi.mIntoBannerTimeIndex = which
                                        SPUtils.putInt(Params.mIntoBannerTimeIndex, DataApi.mIntoBannerTimeIndex)
                                        notifyItemChanged(position)
                                        dialog.dismiss()
                                    }
                                    ?.show()?.apply { DialogUtil.hideNavigationBar(window) }
                            }
                            "每张广告图轮播的时长(单位秒)" -> {
                                AlertDialog.Builder(this@SystemSettingActivity)
                                    .setTitle("请选择时间(单位秒):")
                                    .setCancelable(true)
                                    ?.setSingleChoiceItems(DataApi.mPerBannerImgStayTimeArray, DataApi.mPerBannerImgStayTimeIndex) { dialog, which -> // [1]把选择的条目给取出来
                                        itemBean.rightValue = DataApi.mPerBannerImgStayTimeArray[which]
                                        DataApi.mPerBannerImgStayTimeIndex = which
                                        SPUtils.putInt(Params.mPerBannerImgStayTimeIndex, DataApi.mPerBannerImgStayTimeIndex)
                                        notifyItemChanged(position)
                                        dialog.dismiss()
                                    }
                                    ?.show()?.apply { DialogUtil.hideNavigationBar(window) }
                            }
                            "使用何种AI识别算法" -> {
                                AlertDialog.Builder(this@SystemSettingActivity)
                                    .setTitle("请选择识别算法:")
                                    .setCancelable(true)
                                    ?.setSingleChoiceItems(DataApi.mAiBrandTypeArray, DataApi.mAiBrandTypeIndex) { dialog, which -> // [1]把选择的条目给取出来
                                        itemBean.rightValue = DataApi.mAiBrandTypeArray[which]
                                        DataApi.mAiBrandTypeIndex = which
                                        SPUtils.putInt(Params.mAiBrandTypeIndex, DataApi.mAiBrandTypeIndex)
                                        notifyItemChanged(position)
                                        dialog.dismiss()
                                    }
                                    ?.show()?.apply { DialogUtil.hideNavigationBar(window) }
                            }
                            "授权激活" -> {
                            }
                            "内部设置" -> {
                            }
                            "学习模式" -> {
                            }
                            "商品管理" -> {
                            }
                            "清除全部商品的学习数据" -> {
                            }
                            "版本号" -> {
                                CommUtils.checkUpdateApp01(this@SystemSettingActivity)
                            }
                            else -> ToastUtil.showToast("暂不开放此功能!")
                        }
                    }
                }
            }
        }
    }

    override fun isRegisterEventBus(): Boolean = true

    @SuppressLint("SetTextI18n")
    override fun receiveEvent(event: Event<Any>) {
        super.receiveEvent(event)
        when (event.code) {
            EventCode.BLUETOOTH_PRINT_OPEN_FAILED, EventCode.BLUETOOTH_PRINT_OPEN_SUCCESS -> {
                d("receiveEvent:code->${event.code}")
                refreshList()
            }
            EventCode.BLUETOOTH_PRINT_ENABLE_SETTING -> {
                //蓝牙权限
                try {
                    val enableIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
                    startActivityForResult(enableIntent, BluetoothPrinter.ENABLE_BT)
                } catch (e: Exception) {
                    ToastUtil.showToast("e:$e")
                }
            }
            EventCode.BLUETOOTH_PRINT_START_CHOOSE_DEVICES -> {
                val intent = Intent(this, BluetoothDeviceList::class.java)
                startActivityForResult(intent, BluetoothPrinter.CONNECT_DEVICE)
            }
            EventCode.WEIGHT_DATA_ALL -> {
                mDebugWeightTv.text = (event.data as WeightBean).weightString
            }
            EventCode.READER_CARD_HEX_STRING -> {
                mDebugReaderTv.text = "刷卡：${event.data as String}"
            }
        }
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        return if (KeyboardUtil.onKeyDown(keyCode, event,this)) true else super.onKeyDown(keyCode, event)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        when {
            requestCode == BluetoothPrinter.CONNECT_DEVICE && resultCode == RESULT_OK -> {
                mLoadingDialog.show()
                mLoadingDialog.titleTv.text = "正在连接..."
                //这里获取蓝牙名称和地址
                BluetoothPrinter.mBluetoothPrinterMac = data!!.extras!!.getString(BluetoothPrinter.EXTRA_DEVICE_ADDRESS)
                BluetoothPrinter.mBluetoothPrinterName = data.extras!!.getString(BluetoothPrinter.EXTRA_DEVICE_NAME)
                d("mBluetoothPrinterMac:${BluetoothPrinter.mBluetoothPrinterMac},mBluetoothPrinterName:${BluetoothPrinter.mBluetoothPrinterName}")
                SPUtils.putString(Params.mBluetoothPrinterMac, BluetoothPrinter.mBluetoothPrinterMac)
                SPUtils.putString(Params.mBluetoothPrinterName, BluetoothPrinter.mBluetoothPrinterName)
                EventBusUtil.sendEvent(Event(EventCode.BLUETOOTH_PRINT_OPEN))
            }
        }
    }
}